package com.baicai.baicaiknowledgeai.service.impl;

import com.baicai.baicaiknowledgeai.entity.User;
import com.baicai.baicaiknowledgeai.mapper.UserMapper;
import com.baicai.baicaiknowledgeai.service.IUserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Date;

/**
 * 用户服务实现类
 * @author 白菜
 */
@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public User findByUsername(String username) {
        User one = userMapper.selectOne(new QueryWrapper<User>().eq("username", username));
        if(one == null){
            return null;
        }
        return one;
    }


    @Override
    public User login(String username, String password) {
        User user = findByUsername(username);
        if (user != null) {
            // TODO: 在实际项目中，密码应该是加密存储和比对的
            // 例如使用 Spring Security 的 BCryptPasswordEncoder
            if (user.getPassword().equals(password)) {
                return user;
            }
        }
        return null;
    }

    @Override
    public User register(String username, String password) {
        if (findByUsername(username) != null) {
            // 用户名已存在
            return null;
        }
        User newUser = new User();
        newUser.setUsername(username);
        // TODO: 密码需要加密处理
        newUser.setPassword(password);
        userMapper.insert(newUser);
        return newUser;
    }

    @Override
    public User updateUserForKnowledgeBaseId(User user) {
        user.setUpdateTime(LocalDateTime.now());
        userMapper.updateById(user);
        return user;
    }
}
